/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2025-10-23 17:11:38
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2025-10-24 21:25:05
 * @FilePath: \work-tool\experi-api\middlewares\svg-verify.js
 * @Description: 
 */
const svgCaptcha = require('svg-captcha');
const crypto = require('crypto');
const { redisSet, redisGet, redisDel } = require('../utils/redisStroe');
// const express = require('express');
// const router = express.Router();

// // 验证码路由
// router.get('/verify', (req, res) => {
   
//   const captcha = svgCaptcha.create({
//     size: 4,
//     charPreset: '0123456789',
//     noise: 2,
//     color: true,
//     background: '#cc9966'
//   });

//   res.type('svg');
//   res.status(200).send(captcha.data);
// });



// module.exports = router;
// 生成随机 ID 的函数
function generateRandomId() {
  return crypto.randomUUID ? crypto.randomUUID() : crypto.randomBytes(16).toString('hex');
}

exports.generateCaptcha = async (req, res) => { 
    return new Promise((resolve, reject) => { 
        const captcha = svgCaptcha.create({
            size: 4,
            charPreset: '0123456789',
            noise: 2,
            color: true,
            background: '#cc9966'
        });
        const  id =  generateRandomId();
        redisSet('validateCode', id, 60 * 5)
        resolve({
            id:  id,
            svg: captcha.data
        });
    });
};

exports.verifyCaptcha = async (req, res) => { 
    const { id, value } = req.body;
    const captcha = await redisGet(id);
    if (!captcha) {
        return res.status(400).json({
            success: false,
            message: '验证码已过期，请重新获取'
        });
    }
    if (captcha !== value) {
        return res.status(400).json({
            success: false,
            message: '验证码错误'
        });
    }
    redisDel(id);
    return res.json({
        success: true,
        message: '验证码验证成功'
    });
};
